'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

  /*
  * 查询list
  * Method: get
  * path: /xxxx
  */
  async index() {
    const { ctx, service } = this
    ctx.body = {
      name: 'hry',
      category: 'framework',
      language: 'Node.js'
    }
  }

  /*
  * 根据id查询
  * Method: get
  * path: /xxxx/:id
  */
  async show() {

    const { ctx, service } = this
    
    let query = ctx.request.query

    const res = await ctx.service.user.show({username: ctx.params.id, password: query.password})

    if (res) {
      ctx.helper.returnJson({
        ctx,
        data: res
      })
    } else {
      ctx.helper.returnJson({
        ctx,
        msg: '用户名或密码错误',
        code: 50
      })
    }
  }

  /*
  * 创建
  * Method: post
  * path: /xxxx
  */
  async create() {
    const { ctx, service } = this

    let body = ctx.request.body

    if (!body.captcha || ctx.session.captcha !== body.captcha) {

      const userInfo = await ctx.service.user.show({
        username: body.username
      })

      if (!userInfo) {
        const res = await ctx.service.user.create({
          username: body.username,
          password: body.password,
        })
        ctx.helper.returnJson({
          ctx,
          data: res
        })
      } else {
        ctx.helper.returnJson({
          ctx,
          msg: '用户名已存在',
          code: 50
        })
      }
    } else {
      ctx.helper.returnJson({
        ctx,
        msg: '验证码错误',
        code: 50
      })
    }
  }

  /*
  * 修改更新
  * Method: put
  * path: /xxxx/:id
  */
  async update() {
    const { ctx, service } = this

    let body = ctx.request.body

    const res = await ctx.service.user.update({_id: ctx.session.id}, body)
    
    ctx.helper.returnJson({
      ctx,
      data: res
    })
  }

  /*
  * 删除
  * Method: DELETE
  * path: /xxxx/:id
  */
  async destroy() {
    const { ctx, service } = this
    ctx.body = {
      name: 'hry',
      category: 'framework',
      language: 'Node.js'
    }
  }
}

module.exports = UserController
